<?php

namespace App\Http\Controllers\Backend\Flaw;

use App\Models\Knowledge\Knowledge;
use App\Models\ProjectManage\CheckOption;
use App\Services\Vuls\Distribute;
use App\Models\Access\User\User;
use App\Models\App;
use App\Models\Flaw\Task;
use App\Models\Flaw\VulsDelay;
use App\Services\Vuls\Delay;
use App\Services\Vuls\SendEmail;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Flaw\Vuls;
use App\Models\Flaw\Category;
use App\Models\Flaw\VulsRecord;
use App\Models\Flaw\Level;
use App\Http\Controllers\Traits\Base;

use \App\Models\Log;
use App\Models\Access\Role\Role;

class VulsController extends Controller
{
    use Base;

    /**
     * vulsList 漏洞状态列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function vulsList(Request $request)
    {
        $apps = $this->userLinks();
        //类别为1 则只查询删除后的数据（软删除）
        $type = $request->type ? 1 : 0;
        $colls = Vuls::searchVarCol($apps);
        //统计数据
        $static = Vuls::statusNumber($apps['apps']);
        $static[5] = Vuls::BecommitNumer($apps['apps']);
        //默认不显示‘已忽略’,‘无影响’
        $where[] = ['vuls.status','!=',Vuls::IGNORE];
        $where[] = ['vuls.status','!=',Vuls::NOEFFECT];
        $scopeWhere = $where;
        array_push($scopeWhere,['vuls.user_id','=',Auth::id()]);
        $vlists = $request->type ? Vuls::unionSelect($apps['apps'],array() , array(), array(), false) : Vuls::unionSelect($apps['apps'],$where,[],[],true,$scopeWhere);
        $vlists['paginate'] = Vuls::extendAttr($vlists['paginate']);
        return view('backend.flaw.vulslist', [
                'lists' => $vlists['paginate'],
                'vulStatus' => Vuls::$vulsStatus,
                'ulists' => $colls->ulists,
                'categorys' => $colls->categorys,
                'levels' => $colls->levels,
                'ogzs' => $colls->ogzs,
                'apps' => $colls->apps,
                'app' => -1,
                'type' => $type,
                'static' => $static
            ]
        );
    }

    /**
     * addVuls 提交漏洞操作
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function addVuls(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();
            $validator = Vuls::validate($request->all());
            if ($validator->fails()) {
                return redirect('admin/vulsAdd')
                    ->withErrors($validator)
                    ->withInput();
            }
            $data['vuls_number'] = $this->creatVulsCode();
            $data['user_id'] = Auth::id();
            //clean过滤%的问题
            $data['content'] = clean($request->content, 'user_topic_body');
            $data['status'] = 0;
            htmlspecialchars($request->from_url);
            $fromUrlXss = clean(htmlspecialchars_decode($request->from_url), 'user_topic_body');
            $urlParmsXss = clean($request->url_parms, 'user_topic_body');
            $payload = clean($request->payload, 'user_topic_body');
            $data['form_url'] = $fromUrlXss ? $fromUrlXss : '';
            $data['url_parms'] = $urlParmsXss ? $urlParmsXss : '';
            $data['payload'] = $payload ? $payload : '';
            Vuls::create($data);
            $date = date('Y');
            DB::insert("INSERT INTO vuls_count (year,count) VALUES ($date,1) ON DUPLICATE KEY UPDATE count=count+1");
            return redirect('/admin/vulsList');
        } else {
            $category = new Category;
            $apps = $this->userLinks();
            $categorys = $category->getCategoryInfo();
            $users = DB::table('users')->select('id', 'real_name')->get();
            $levels = Level::withoutTrashed()->select('id', 'level', 'name')->get();
            $apps = DB::table('app')->select('id', 'ogz_id', 'name')->whereIn('id', $apps['apps'])->get();
            $vulStatus = config('app.vul.status');
            $vulCheckOption = CheckOption::listForSelect();
            return view('backend.flaw.vulsadd', [
                'action' => 'add',
                'categorys' => $categorys,
                'users' => $users,
                'levels' => $levels,
                'apps' => $apps,
                'vulstatus' => $vulStatus,
                'vulCheckOption' => $vulCheckOption,
                'app_id'=>intval($request->app_id),
                'check_id'=>intval($request->check_id)
            ]);
        }
    }

    /**生成漏洞编码
     * @return string
     */
    private function creatVulsCode()
    {
        $year = date('Y');
        $vuls = DB::table('vuls_count')
            ->where('year', $year)
            ->select('count')
            ->get()
            ->toArray();
        $years = $this->selectYear($year);
        if (empty($vuls)) {
            $code = "HVE-" . $years . '-0001';
        } else {
            $count = $vuls[0]->count;
            $count += 1;
            $num = str_pad($count, 4, 0, STR_PAD_LEFT);
            $code = "HVE-" . $years . '-' . $num;
        }
        return $code;

    }

    private function selectYear($year)
    {
        $result = strpos($year, "0", 0);
        if ($result) {
            $result = $result + 1;
        }
        $years = substr($year, $result);
        return $years;
    }

    /**
     * updateVuls 更新漏洞操作
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function updateVuls(Request $request)
    {
        if ($request->isMethod('post')) {
            $validator = Vuls::validate($request->all());
            if ($validator->fails()) {
                return redirect('admin/vulsUpdate/id/' . $request->id)
                    ->withErrors($validator)
                    ->withInput();
            }
            $save = Vuls::find($request->id);
            $save->title = $request->title;
            $save->user_id = Auth::id();
            $save->app_id = $request->app_id;
            $save->category_id = $request->category_id;
            $save->content = clean($request->content, 'user_topic_body');
            /*            $save->reward = $request->reward;
                        $save->credit = $request->credit;*/
            $save->status = $request->status;
            $save->description = $request->description;
            $fromUrlXss = clean($request->from_url, 'user_topic_body');
            $urlParmsXss = clean($request->url_parms, 'user_topic_body');
            $payload = clean($request->payload, 'user_topic_body');
            $save->form_url = $fromUrlXss ? $fromUrlXss : '';
            $save->url_parms = $urlParmsXss ? $urlParmsXss : '';
            $save->payload = $payload ? $payload : '';
            $save->save();
            return redirect('/admin/vulsList');
        } else {
            $category = new Category;
            $apps = $this->userLinks();
            $categorys = $category->getCategoryInfo();
            $users = DB::table('users')->select('id', 'real_name', 'name')->get();
            $levels = DB::table('level')->select('id', 'level', 'name')->get();
            $vulStatus = config('app.vul.status');
            $item = Vuls::where(['id'=>$request->id])->whereIn('app_id',$apps['apps'])->first();
            if ($item){

                $item->content = overwriteConetnt($request,$item->content, Auth::user()->real_name);
                //价值
                $item->vlus_value = Vuls::getValue($item->level_id);
                //检查项
                if (intval($item->check_id) > 0){
                    $item->checkStr = CheckOption::where(['id'=>$item->check_id])->value('name');
                }
                //参考资料
                $item->ref = Knowledge::where(['category_id'=>$item->category_id])->get();
            }
            $apps = DB::table('app')->select('id', 'ogz_id', 'name')->whereIn('id', $apps['apps'])->get();
            if (!$request->is('*vulsDetail/*')) {
                return view('backend.flaw.vulsadd', [
                        'item' => $item,
                        'action' => 'update',
                        'categorys' => $categorys,
                        'users' => $users,
                        'levels' => $levels,
                        'apps' => $apps,
                        'vulstatus' => $vulStatus,
                    ]
                );
            } else {
                $vulsRecords = vulsRecord::getVulsRecords($request->id);
                return view('backend.flaw.vulsdetail', [
                        'item' => $item,
                        'action' => 'detail',
                        'categorys' => $categorys,
                        'users' => $users,
                        'levels' => $levels,
                        'apps' => $apps,
                        'vulstatus' => $vulStatus,
                        'vulsRecords' => $vulsRecords,
                    ]
                );
            }
        }
    }

    /**
     * delVuls 删除漏洞操作
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function delVuls(Request $request)
    {
        $del = Vuls::find($request->id);
        $del->is_delete = 1;
        $del->delete_at = date('Y-m-d H:i:s', time());
        $del->save();
        $del->delete();
        return redirect('/admin/vulsList');
    }

    /**
     * restoreVuls  从回收站中恢复删除的漏洞
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function restoreVuls(Request $request)
    {
        Vuls::withTrashed()->where('id', $request->id)->restore();
        return back();
    }

    /**
     * forceDelVuls 物理删除，在数据库清除此条记录
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function forceDelVuls(Request $request)
    {
        Vuls::withTrashed()->where('id', $request->id)->forceDelete();
        return back();
    }

    /**
     * sentencePointsVuls 重判等级评分
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sentencePointsVuls(Request $request)
    {
        if (empty($request->status)) return false;
        $vulsFind = Vuls::find($request->vulsid);
        $vulsFind->is_reasonable = $request->status;
        $vulsFind->save();
        //为3时，即漏洞等级设置不合理，需修改时，添加漏洞操作记录
        if ($request->status == 3) {
            $isExists = VulsRecord::where([['vuls_id', $request->vulsid], ['is_reasonable', '3']])->first();
            //不存在增加记录，存在则修改理由
            if ($isExists == null) {
                $data = [
                    'app_id' => $vulsFind->app_id,
                    'vuls_id' => $request->vulsid,
                    'vuls_status' => $vulsFind->status,
                    'content' => $request->desc,
                    'created_by' => Auth::id(),
                    'is_reasonable' => $request->status,
                ];
                VulsRecord::create($data);
            } else {
                $update = VulsRecord::find($isExists->id);
                $update->content = $request->desc;
                $update->save();
            }
        }
        return collect(['code' => 0, 'msg' => 'success'])->toJson();
    }

    /**
     * getPointsAjax  返回当前等级相关信息
     *
     * @param Request $request
     * @return mixed
     */
    public function getPointsAjax(Request $request)
    {
        $returnInfo = array();
        $list = DB::table('level')->find($request->id);
        $returnInfo['min'] = $list->min_integ;
        $returnInfo['min_r'] = $list->min_reward;
        $returnInfo['max'] = $list->max_integ;
        $returnInfo['max_r'] = $list->max_reward;
        return $returnInfo;
    }

    /**
     * vulsReedit 重新编辑等级、状态
     *
     * @param Request $request
     * @return bool|string
     */
    public function vulsReedit(Request $request)
    {
        if (empty($request->vulsid)) return false;
        $list = Level::where('id', $request->level)->first();
        //验证当前积分是否超出改等级限额
        if ($request->points < $list->min_integ || $request->points > $list->max_integ) {
            return collect(['code' => 100, 'msg' => '积分超出等级限额，更新失败'])->toJson();
        } elseif ($request->rewards < $list->min_reward || $request->rewards > $list->max_reward) {
            return collect(['code' => 101, 'msg' => '安全币超出等级限额，更新失败'])->toJson();
        }
        $vulsFind = Vuls::find($request->vulsid);
        $vulsFind->level_id = $request->level;
        $vulsFind->credit = $request->points;
        $vulsFind->reward = $request->rewards;
        //更改玩等级、积分后状态变为待确认状态
        $vulsFind->is_reasonable = 1;
        $vulsFind->save();
        return collect(['code' => 0, 'msg' => 'success'])->toJson();
    }

    /**
     * auditVuls 审核漏洞操作
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function auditVuls(Request $request)
    {
        if ($request->isMethod('post')) {
            $validator = VulsRecord::validate($request->all());
            if ($validator->fails()) {
                return redirect('admin/vulsAudit/id/' . $request->vuls_id)
                    ->withErrors($validator)
                    ->withInput();
            }
            $updateVuls = Vuls::find($request->vuls_id);
            $updateVuls->status = 2;
            $updateVuls->save();
            $data = $request->all();
            $data['created_at'] = date('Y-m-d H:i:s', time());
            $data['user_id'] = Auth::id();
            $data['updated_at'] = date('Y-m-d H:i:s', time());
            $data['created_by'] = Auth::id();
            $data['update_by'] = Auth::id();
            VulsRecord::create($data);
            return redirect('/admin/vulsList');
        } else {
            $list = DB::table('vuls')
                ->where('vuls.id', '=', $request->id)
                ->select('vuls.id', 'vuls.title', 'vuls.app_id')
                ->first();
            return view('backend.flaw.vulsaudit', [
                'item' => $list,
            ]);
        }


    }

    /**
     * 待确认步骤中，分为两个操作，分派、申诉。对应的状态码为配置中vul中的id值
     * 分为首次执行和更新
     * @param Request $request
     */
    public function ensureForm(Request $request)
    {
        $validator = $this->validate($request, [
            'description' => 'required|max:255',
//            'allocation' => 'required|integer',
            'id' => 'required|integer',
        ], [
                "description.max" => "描述长度不可以超过225个字符<br>",
                "description.required" => "描述为必填项<br>",
//                "allocation.required" => "分派为必填项<br>",
//                "allocation.numeric" => "分派类型不正确<br>",
                "id.required" => "请提交对应漏洞项<br>",
                "id.numeric" => "漏洞项类型不正确<br>",
            ]
        );
        $vuls = $this->getVuls($request->id);
        $vuls = $vuls->toArray();
        if (isset($vuls[0])){

            $visit = $this->legal($vuls[0]->status, 'ensure');
        }
        if (!isset($visit)) {
            return abort(404);
            exit();
        }
        $oporate = $request->appeal;//两个动作：分派、申诉
        $status = config('app.vul');//获取状态码配置

        $updateData = array();
        $updateData = [
            'vuls_id' => $request->id,
            'app_id' => $vuls[0]->app_id,
            'content' => $request->description,
            'reward' => $vuls[0]->reward,
            'credit' => $vuls[0]->credit,
        ];
        if (!$oporate)//执行分派动作
        {

            $updateData ['vuls_status'] = $status["status"]["3"]["id"];
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;

            $vulsData['status'] = $status["status"]["3"]["id"];//漏洞状态更新为待修复
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());
            $vulsData['is_reasonable'] = 1;
            $recordUdp = DB::table('vuls_record')->insert(
                $updateData
            );
            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);
            /*-------------发送邮件服务-----------*/
        } else {//申诉动作

            $record = DB::table('vuls_record')
                ->where(array('vuls_id' => $request->id, 'vuls_status' => $status["status"]["7"]["id"]))
                ->count();

            $updateData ['vuls_status'] = $status["status"]["7"]["id"];//记录状态申诉中
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;
            $vulsData['status'] = $status["status"]["7"]["id"];//漏洞状态更新为待修复
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $recordUdp = DB::table('vuls_record')->insert(
                $updateData
            );

            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);

        }

        return redirect('/admin/vulsList');

    }


    /**已修复信息提交
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function repairForm(Request $request)
    {
        $validator = $this->validate($request, [
            'description' => 'required|max:255',
            'id' => 'required|integer'
        ], [
            "description.max" => "描述长度不可以超过225个字符<br>",
            "description.required" => "描述为必填项<br>",
            "id.required" => "请提交对应漏洞项<br>",
            "id.integer" => "漏洞项类型不正确<br>",
        ]);
        $status = config('app.vul');//获取状态码配置
        $record = DB::table('vuls_record')
            ->where(array('vuls_id' => $request->id, 'vuls_status' => $status["status"]["4"]["id"]))//修复提交
            ->count();
        $app_id = Vuls::where(array('id' => $request->id))
            ->select('app_id', 'status', 'reward', 'credit')
            ->get();
        $app_id = $app_id->toArray();
        $visit = $this->legal($app_id[0]['status'], "repairshow");//判断当前的页面访问是否合法
        if (!$visit) {
            return abort(404);
            exit();
        }
        $updateData = [
            'vuls_id' => $request->id,
            'content' => $request->description,
            'app_id' => $app_id[0]['app_id']
        ];
        $updateData['reward'] = $app_id[0]['credit'];
        $updateData['credit'] = $app_id[0]['reward'];

        $updateData ['vuls_status'] = $status["status"]["4"]["id"];
        $updateData ['created_at'] = date('Y-m-d H:i:s', time());
        $updateData ['created_by'] = Auth::id();;
        $vulsData['status'] = $status["status"]["4"]["id"];//漏洞状态更新为待修复
        $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
        $recordUdp = DB::table('vuls_record')->insert(
            $updateData
        );
        $vulsUdp = DB::table('vuls')
            ->where('id', $request->id)
            ->update($vulsData);

        return redirect('/admin/vulsList');
    }

    /**待审核页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function check(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.check';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'check');//判断当前的页面访问是否合法
            }
            $category = new Category;
            $categorys = $category->getCategoryInfo();
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            $lists = DB::table('app')
                ->select('name', 'id')
                ->get();
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
                    'level' => $level,
                    'categorys' => $categorys,
                    'list' => $lists,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**待确认页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function ensure(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.ensure';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'ensure');//判断当前的页面访问是否合法
            }

            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            $lists = DB::table('app')
                ->where("id", $vuls[0]->app_id)
                ->select('name', 'id')
                ->get()
                ->toArray();
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
                    'level' => $level,
                    'list' => $lists[0],
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**待修复页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function repair(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.repairshow';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'repairshow');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
//                    'level'=>$level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**获取指定id用户角色组
     * @param $id
     * @return bool
     */
    public function getRole($id)
    {
        if (empty($id)) return false;
        return DB::table("assigned_roles")->where("user_id", $id)->pluck("role_id")->toArray();
    }

    /**修复确认页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function confirm(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $user_id = Auth::id();//用户id
            $role = $this->getRole($user_id);
            /*-----------过滤超级管理员--------------*/
            if (in_array(1, $role)) {
                $show = 'backend.flaw.confirmshow';
            } else {
                if (access()->allow("vuls-confirmForm")) {
                    $show = 'backend.flaw.confirmshow';
                } elseif (access()->allow("vuls-confirmView")) {
                    $show = 'backend.flaw.confirmview';
                }
            }
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];

            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'confirmshow');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
//                    'level'=>$level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**已解决页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function solved(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.shutdown';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'solved');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
//                    'level'=>$level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**已忽略页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function ignore(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.shutdown';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'ignore');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
//                    'level'=>$level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**无影响页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function noEffect(Request $request)
    {
        $id = intval($request->id);//漏洞ID

        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.shutdown';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'noEffect');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
//                    'level'=>$level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**已关闭界面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function shut(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.shut';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'shut');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
                    'level' => $level,
                ]
            );
        } else {
            return abort(404);
        }

    }

    /**已忽略页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function appeal(Request $request)
    {
        $id = intval($request->id);//漏洞ID
        if ($id) {
            $access = access()->allow("vuls-appealForm");
            if (!$access) {
                $disable = 1;
            } else {
                $disable = 0;
            }
            $result = $this->statusData($id,$request);
            $vuls = $result['vuls'];
            $level = $result['level'];
            $record = $result['record'];
            $status = $result['status'];
            $show = 'backend.flaw.appeal';
            $vulsInfo = $vuls->toArray();
            if (isset($vulsInfo[0])){

                $visit = $this->legal($vulsInfo[0]->status, 'appeal');//判断当前的页面访问是否合法
            }
            if (!isset($visit)) {
                return abort(404);
                exit();
            }
            $lists = DB::table('app')
                ->select('name', 'id')
                ->get();
            return view($show, [
                    'id' => $id,
                    'vuls' => $vuls,
                    'record' => $record,
                    'status' => $status['status'],
                    'level' => $level,
                    'disable' => $disable,
                    'list' => $lists,
                ]
            );
        } else {
            return abort(404);
        }

    }

    private function statusData($id,$request='')
    {
        if ($id) {
            $status = config('app.vul');//获取状态码配置
            $access = access()->hasApps();
            $vuls = DB::table('vuls')
                ->join('level', 'level.id', '=', 'vuls.level_id')
                ->leftJoin('users', 'users.id', '=', 'vuls.user_id')
                ->where('vuls.id', '=', $id)
                ->whereIn('vuls.app_id',$access)
                ->select('vuls.id', 'vuls.status', 'vuls.level_id', 'vuls.title', 'vuls.content', 'vuls.description', 'vuls.app_id', 'level.min_reward', 'level.max_reward', 'level.min_integ', 'level.max_integ', 'vuls.reward', 'vuls.credit', 'vuls.vuls_number', 'vuls.category_id', 'users.source', 'vuls.form_url', 'vuls.payload', 'vuls.url_parms')
                ->get();
            $vuls[0]->ref = Knowledge::where(['category_id'=>$vuls[0]->category_id])->get();
            if ($request){

                $vuls[0]->content = overwriteConetnt($request,$vuls[0]->content, Auth::user()->real_name);
            }
            $level = DB::table('level')
                ->get();
            //日志记录
            $record = DB::select("SELECT	a.*,b.id AS bid,b.phone,	b.name as creatname,b.real_name as creal_name,c.real_name as ureal_name,c.name as updatename FROM  vuls_record AS a LEFT JOIN users AS b ON a
.created_by = b.id LEFT JOIN users AS c ON a.update_by = c.id  where a.vuls_id = :id ORDER by a.id desc", ['id' => $id]);

            $record_list=[];
            if($record){

                foreach ($record as $value)
                {
                    $phone="";
                    if ($value->phone) {
                            $phone = decrypt_func($value->phone, $value->creatname) ;
                        $value->phone=$phone;
                            }
                    $record_list[]=$value;
                }
            }$records = count($record_list) ? $record_list : false;
            $result['vuls'] = $vuls;
            $result['level'] = $level;
            $result['record'] = $records;
            $result['status'] = $status;
            return $result;
        } else {
            return null;
        }

    }


    /**
     * 已修复步骤中，分为两个操作，重新确认、已解决。对应的状态码为配置中vul中的id值
     * 分为首次执行和更新
     * @param Request $request
     */
    public function confirmForm(Request $request)
    {
        $validator = $this->validate($request,
            ['description' => 'bail|required|max:255',
                'id' => 'bail|required|integer'],
            [
                "description.max" => "描述长度不可以超过225个字符<br>",
                "description.required" => "描述为必填项<br>",
                "id.required" => "请提交对应漏洞项<br>",
                "id.integer" => "漏洞项类型不正确<br>",
            ]
        );
        $oporate = $request->Reconfirmation;//两个动作：重新确认、已解决
        $status = config('app.vul');//获取状态码配置
        $vuls = $this->getVuls($request->id);
        $vuls = $vuls->toArray();
//        $app_id = Vuls::where(array('id' => $request->id))
//            ->select('app_id', 'reward', 'credit', 'user_id', 'status', 'app_id', 'title')
//            ->get();
//        $app_id = $app_id->toArray();
        if (isset($vuls[0])){

            $visit = $this->legal($vuls[0]->status, "confirmshow");//判断当前的页面访问是否合法
        }
        if (!isset($visit)) {
            return abort(404);
            exit();
        }
        $updateData = array();
        $updateData = [
            'vuls_id' => $request->id,
            'app_id' => $vuls[0]->app_id,
            'content' => $request->description,
        ];

        $updateData['reward'] = $vuls[0]->credit;
        $updateData['credit'] = $vuls[0]->reward;
        if (!$oporate)//执行已解决动作
        {
            $vulsAbout = $this->getVuls($request->id);
            if ($vulsAbout) {
                if ($vulsAbout[0]->source == 1) //内部提交的漏洞直接把评分设为合理
                {
                    $vulsData['is_reasonable'] = 2;
                }
            }
            $updateData ['vuls_status'] = $status["status"]["5"]["id"];
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;
            $vulsData['status'] = $status["status"]["5"]["id"];//漏洞状态更新为已解决
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $recordUdp = DB::table('vuls_record')->insert(
                $updateData
            );
            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);
            //        /*----------发送邮件-------------*/
            $config = config('email.cansend');
            if ($config) {
                $vulevel = DB::table('level')
                    ->where('id', '=', $vuls[0]->level_id)
                    ->get()
                    ->toArray();
                //        //查询app，ogz相关信息，以及相关人员信息
                $vuogz = DB::table('app')
                    ->join('ogz as a', 'app.ogz_id', '=', 'a.id')
                    ->select('app.name as appname', 'app.user_id as  appusers', 'a.name as ogzname')
                    ->where('app.id', '=', $vuls[0]->app_id)
                    ->get()
                    ->toArray();
                $appuser = $vuogz[0]->appusers;
                if ($appuser) {
                    $appUserId = explode(',', $appuser);
                    $appUserInfo = DB::table('users')
                        ->whereIn('id', $appUserId)
                        ->get()
                        ->toArray();

                    $email = "";
                    $userName = "";
                    if ($appUserInfo) {
                        foreach ($appUserInfo as $value) {
                            $email .= decrypt_func($value->email, $value->name);
                            $email .= ",";
                            $userName .= $value->name . ",";
                        }
                        $email = trim($email, ",");
                        $userName = trim($userName, ",");
                        if ($email) {
                            $vulsInfo = array();
                            $vulsInfo['vulsid'] = $request->id;//漏洞id
                            $vulsInfo['appid'] = $vuls[0]->app_id;//漏洞id
                            $vulsInfo['vuls_number'] = $vuls[0]->vuls_number;//漏洞id
                            $vulsInfo['level_name'] = $vulevel[0]->name;//漏洞等级
                            $vulsInfo['level_id'] = $vuls[0]->level_id;//漏洞等级
                            $vulsInfo['user'] = $userName;//漏洞id
                            $vulsInfo['appname'] = $vuogz[0]->appname;//漏洞id
                            $vulsInfo['title'] = $vuls[0]->title;//漏洞名称
                            $vulsInfo['sendtype'] = 2;//修复确认邮件类型
                            $vulsInfo['useremail'] = $email;//收件人邮箱
                            $vulsInfo['time'] = date("Y年m月d日", time());
                            $vulsInfo['source'] = $vuls[0]->source;//漏洞来源
                            $vulsInfo['description'] = $vuls[0]->description;//漏洞副标题
                            $vulsInfo['user_id'] = $vuls[0]->user_id;;//提交人
                            DB::table('task')->where(['vulsid'=>$request->id])->update(
                                $vulsInfo
                            );
                        }
                    }
                }
            }


        } else {//重新确认
//            $records = VulsRecord::where(array('vuls_id' => $request->id, 'vuls_status' =>
//                $status["status"]["2"]["id"]))
//                ->select('id')
//                ->get();
//            $records = $records->toArray();
            $updateData ['vuls_status'] = $status["status"]["3"]["id"];//待确认
            $updateData ['updated_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $vulsData['status'] = $status["status"]["3"]["id"];//漏洞状态更新为待修复
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $recordUdp = DB::table('vuls_record')
                ->insert($updateData);

            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);
            //发送未修复及时邮件
            Vuls::unconfirmEmail($vuls[0]);
        }
        return redirect('/admin/vulsList');

    }

    /**
     * 关闭
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function shutDownForm(Request $request)
    {
        $validator = $this->validate($request, [
            'description' => 'required|max:255',
            'id' => 'required|integer'
        ],
            [
                "description.max" => "描述长度不可以超过225个字符",
                "description.required" => "描述为必填项",
                "id.required" => "请提交对应漏洞项",
                "id.integer" => "漏洞项类型不正确",
            ]);

        /*-------------判断当前状态是否可以关闭---------------*/
        $vuls = $this->getVuls($request->id);
        if (!isset($vuls)){
            return abort(404);
            exit();
        }
        $vuls = $vuls->toArray();
        if ($vuls[0]->source != 1)   //外部提交漏洞
        {
            if ($vuls[0]->status == 5) {
                $judge_state = $vuls[0]->is_reasonable;
                if ($judge_state != 2) {
                    return back()->with("flow_error", "评级评分尚未结束");
                    exit();
                }
            }
        }

        $current = $vuls[0]->status;

        $states = [5, 8, 11];
        if (!in_array($current, $states)) {
            return abort(404);
            exit();
        }

        $visit = $this->legal(5, "solved");//判断当前的页面访问是否合法
        if (!$visit) {
            return abort(404);
            exit();
        }
        $status = config('app.vul');//获取状态码配置

        $updateData = array();
        if ($vuls) //经过分派流程
        {
            $updateData = [
                'vuls_id' => $request->id,
                'app_id' => $vuls[0]->app_id,
                'content' => $request->description,
            ];
        } else { //经过申诉流程
            $updateData = [
                'vuls_id' => $request->id,
                'content' => $request->description,
            ];
        }
        $updateData['reward'] = $vuls[0]->credit;
        $updateData['credit'] = $vuls[0]->reward;

        $updateData ['vuls_status'] = $status["status"]["6"]["id"];
        $updateData ['created_at'] = date('Y-m-d H:i:s', time());
        $updateData ['created_by'] = Auth::id();;
        $vulsData['status'] = $status["status"]["6"]["id"];//漏洞状态更新为关闭closed_at
        $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
        $vulsData['closed_at'] = date('Y-m-d H:i:s', time());;
        $recordUdp = DB::table('vuls_record')->insert(
            $updateData
        );
        $vulsUdp = DB::table('vuls')
            ->where('id', $request->id)
            ->update($vulsData);

        if ($vuls[0]->source != 1)   //外部提交漏洞，为用户发放金币和积分
        {
            if ($vuls[0]->status == 5) {
                /*------------用户发放金币和积分------------*/
                /*-------金币------*/
                $reward = array();//金币
                $reward['user_id'] = $vuls[0]->user_id;//提交者id
                $reward['params'] = $vuls[0]->reward;//金币
                $reward['created_by'] = Auth::id();
                $reward['type'] = 1;
                $reward['app_id'] = $vuls[0]->app_id;//漏洞应用id
                $reward['vuld_id'] = $request->id;//漏洞id
                /*-------积分------*/
                $credit = array();//积分
                $credit['user_id'] = $vuls[0]->user_id;//提交者id
                $credit['params'] = $vuls[0]->credit;//积分
                $credit['created_by'] = Auth::id();
                $credit['type'] = 2;
                $credit['app_id'] = $vuls[0]->app_id;//漏洞应用id
                $credit['vuld_id'] = $request->id;//漏洞id
                /*———————————个人积分金币记录———————————————*/
                DB::table('reward_log')->insert([$reward, $credit]);
                /*————————————个人积分金币变化——————————————*/
                $vulsUser = DB::table('users')
                    ->where('id', $vuls[0]->user_id)
                    ->first();
                $user_data["credit"] = $vulsUser->credit + $vuls[0]->credit; //个人积分增加
                $user_data["reward"] = $vulsUser->reward + $vuls[0]->reward;//个人金币增加
                $vulsUdp = DB::table('users')
                    ->where('id', $vuls[0]->user_id)
                    ->update($user_data);
                /*—————————————个人积分记录表变化———————————————————*/
                $year = date("Y");
                $month = date("m");
                //查询该漏洞提交者当前年份月份，是否有记录
                $vulsUser = DB::table('credit_edition')
                    ->where([['user_id', $vuls[0]->user_id], ["year", $year], ["month", $month]])
                    ->first();
                $data_credit['user_id'] = $vuls[0]->user_id;
                $data_credit['category_id'] = $vuls[0]->category_id;
                $data_credit['credit'] = $user_data["credit"];
                /*———————————————查看最新一条记录——————————————————*/
                $last = DB::table('credit_edition')
                    ->where('user_id', $vuls[0]->user_id)
                    ->orderBy('id', 'desc')
                    ->first();
                if ($last) {
                    $lastYear = $last->year;
                    $lastMonth = $last->month;
                }
                if (!$vulsUser)  //当前年份、月份、该用户没有积分记录的情况下
                {
                    /*————判断当前用户的最新一条数据是否是当前年份的————*/
                    if ($last) {
                        if ($lastYear == $year) {
                            /*++++++++++++当前年份该用户有数据+++++++++++*/
                            $data_credit['year_credit'] = $vuls[0]->credit + $last->year_credit;
                        }
                    } else {
                        $data_credit['year_credit'] = $vuls[0]->credit;
                    }

                    $data_credit['year'] = $year;
                    $data_credit['month'] = $month;
                    $data_credit['month_credit'] = $vuls[0]->credit;
                    $recordUdp = DB::table('credit_edition')->insert(
                        $data_credit
                    );
                } else {//当前年份、月份、该用户有积分记录的情况下
                    $data_credit['year_credit'] = $vuls[0]->credit;
                    $data_credit['year'] = $year;
                    $data_credit['month'] = $month;
                    $data_credit['updated_at'] = date("Y-m-d H:i:s");
                    $data_credit['month_credit'] = $vuls[0]->credit;
                    $recordUdp = DB::table('credit_edition')
                        ->where('id', $vulsUser->id)
                        ->update($data_credit);
                }
            }
        }

        return redirect('/admin/vulsList');
    }


    /**
     * 申诉步骤中两个操作：驳回，关闭
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function appealForm(Request $request)
    {
        $access = access()->allow("vuls-appealFormView");
        if (!$access) {
            return abort(404);
            exit();
        }
        $validator = $this->validate($request, [
            'description' => 'required|max:255',
            'id' => 'required|numeric',
            'credit' => 'integer',
            'level' => 'integer',
            'allocation' => 'required|integer',
        ],
            [
                "description.max" => "描述长度不可以超过225个字符<br>",
                "description.required" => "描述为必填项<br>",
                "id.required" => "请提交对应漏洞项<br>",
                "id.numeric" => "漏洞项类型不正确<br>",
                "level.integer" => "请选择漏洞等级<br>",
                "credit.integer" => "非法积分值<br>",
                "allocation.required" => "分派为必填项<br>",
                "allocation.numeric" => "分派类型不正确<br>",
            ]);
        $oporate = trim($request->op);
        $status = config('app.vul');//获取状态码配置
        $vuls = $this->getVuls($request->id);
        $vuls = $vuls->toArray();
        $updateData = [
            'vuls_id' => $request->id,
            'content' => $request->description,
            'app_id' => $request->allocation,
        ];
        $vulsData = ['app_id' => $request->allocation, 'description' => $request->subtitle];
        //执行关闭动作
        if ($oporate=='shutdown')
        {
            $updateData ['vuls_status'] = $status["status"]["6"]["id"];
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();
            //v1.8需求更改为已忽略
            $vulsData['status'] = $status["status"]["8"]["id"];
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $recordUdp = DB::table('vuls_record')->insert(
                $updateData
            );
            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);

        }
        //驳回
        if ($oporate=='back'){

            if ($vuls[0]->source == 1)//内部提交漏洞
            {
                $validator = $this->validate($request, [
                    'level' => 'required'
                ],
                    [
                        "level.required" => "请选择漏洞等级<br>"
                    ]);
                if ($request->level) {
                    $max_min = $this->getMaxAndMin($request->level);
                    if (!$max_min) {
                        return back()->with("flow_error", "当前漏洞等级不存在");
                        exit();
                    }
                    $vulsData['level_id'] = $request->level;//漏洞等级更新
                }
            } else { //外部提交漏洞
                $validator = $this->validate($request, [
                    'credit' => 'required',
                    'level' => 'required'
                ],
                    [
                        "level.required" => "请选择漏洞等级<br>",
                        "credit.required" => "请选择积分值<br>",
                    ]);
                if ($request->level) {
                    $max_min = $this->getMaxAndMin($request->level);
                    if (!$max_min) {
                        return back()->with("flow_error", "当前漏洞等级不存在");
                        exit();
                    }
                    if ($request->credit) {
                        $creditChecked = $this->checkMaxAndMin($max_min, (int)$request->credit, "credit");
                        if (!$creditChecked) {
                            return back()->with("flow_error", "积分必须在给定范围内");
                            exit();
                        }
                        $vulsData['credit'] = $request->credit;//漏洞积分更新
                        $updateData['credit'] = $request->credit;//漏洞积分更新
                        $vulsData['reward'] = $request->credit;//漏洞金币更新
                        $updateData['reward'] = $request->credit;//漏洞金币更新
                    }
                    $vulsData['level_id'] = $request->level;//漏洞等级更新
                }
            }

            $records = VulsRecord::where(array('vuls_id' => $request->id, 'vuls_status' =>
                $status["status"]["2"]["id"]))
                ->select('id')
                ->get();
            $records = $records->toArray();
            $updateData ['vuls_status'] = $status["status"]["2"]["id"];//待确认
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;
            $vulsData['status'] = $status["status"]["2"]["id"];//漏洞状态更新为待确认
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $recordUdp = DB::table('vuls_record')
                ->insert($updateData);

            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);
            //驳回信息邮件
            Vuls::rejectEmail($vuls[0]);
        }
        //重新分配
        if ($oporate=='reallocation'){
            $vulsData['id'] = $request->id;
            $vulsData['status'] = $status["status"]["2"]["id"];
            $vulsData['updated_at'] = Carbon::now();
            if (!Vuls::reallocation($vulsData,$updateData)){
                \Log::info('vuls['.$request->id.'] reallocation failed.');
            }
            //task邮件队列应用更新
            if (!Task::resetApp($request->allocation,$request->id)){
                \Log::info('appeal vul['.$request->id.'] reset app task for email failed.');
            }
        }
        return redirect('/admin/vulsList');

    }


    /**
     * 待审核步骤中三个个操作：审核，忽略，无影响
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function checkForm(Request $request)
    {
        $validator = $this->validate($request, [
            'descriptions' => 'required|max:255',
            'id' => 'required|integer',

        ], [
            "descriptions.max" => "描述长度不可以超过225个字符<br>",
            "descriptions.required" => "描述为必填项<br>",
            "id.required" => "请提交对应漏洞项<br>",
            "id.integer" => "漏洞项类型不正确<br>",

        ]);

        $status = config('app.vul');//获取状态码配置
        $vuls = $this->getVuls($request->id);
        $vuls = $vuls->toArray();
        if (isset($vuls[0])){

            $visit = $this->legal($vuls[0]->status, 'check');
        }
        if (!isset($visit)) {
            return abort(404);
            exit();
        }
        $oporate = $request->type;
        switch ($oporate) {
            case 'check':
                if ($vuls[0]->source != 1) //非内部提交
                {
                    $validator = $this->validate($request, [
                        'credit' => 'required|integer',
                        'level' => 'required|integer',
                        'allocation' => 'required|integer',
                    ],
                        [
                            "credit.required" => "请选择积分<br>",
                            "level.required" => "请选择漏洞等级<br>",
                            "level.integer" => "请选择漏洞等级<br>",
                            "credit.integer" => "非法积分值<br>",
                            "allocation.required" => "分派为必填项<br>",
                            "allocation.numeric" => "分派类型不正确<br>",
                        ]);
                    if ($request->level) {
                        $max_min = $this->getMaxAndMin($request->level);
                        if (!$max_min) {
                            return back()->with("flow_error", "当前漏洞等级不存在");
                            exit();
                        }
                        if ($request->credit) {
                            $creditChecked = $this->checkMaxAndMin($max_min, (int)$request->credit, "credit");
                            if (!$creditChecked) {
                                return back()->with("flow_error", "积分必须在给定范围内");
                                exit();
                            }
                            $vulsData['credit'] = $request->credit;//漏洞积分更新
                            $updateData['credit'] = $request->credit;//漏洞积分更新
                            $vulsData['reward'] = $request->credit;//漏洞金币更新
                            $updateData['reward'] = $request->credit;//漏洞金币更新
                        }
                        $vulsData['level_id'] = $request->level;//漏洞等级更新
                    }
                } else {
                    //内部提交漏洞不需要分配积分和金币
                    $validator = $this->validate($request, [
                        'level' => 'required|integer',
                        'allocation' => 'required|integer',
                    ],
                        [
                            "level.required" => "请选择漏洞等级<br>",
                            "level.integer" => "请选择漏洞等级<br>",
                            "allocation.required" => "分派为必填项<br>",
                            "allocation.numeric" => "分派类型不正确<br>",
                        ]);
                    if ($request->level) {
                        $max_min = $this->getMaxAndMin($request->level);
                        if (!$max_min) {
                            return back()->with("flow_error", "当前漏洞等级不存在");
                            exit();
                        }
                        $vulsData['level_id'] = $request->level;//漏洞等级更新
                    }
                }
                $vulsData['app_id'] = $request->allocation;
                $state = $status["status"]["2"]["id"];
                break;
            case 'ignore':
                $state = $status["status"]["8"]["id"];
                break;
            case 'effect':
                $state = $status["status"]["11"]["id"];
                break;
        }

        $app_id = Vuls::where(array('id' => $request->id))
            ->select('app_id')
            ->get();
        $app_id = $app_id->toArray();
        //此处分辨有无app_id
        if (count($app_id)) {
            $updateData['vuls_id'] = $request->id;
            $updateData['app_id'] = $app_id[0]['app_id'];
            $updateData['content'] = $request->descriptions;
        } else {
            $updateData['vuls_id'] = $request->id;
            $updateData['content'] = $request->descriptions;
        }

        if ($oporate) {
            $updateData ['vuls_status'] = $state;
            $updateData ['created_at'] = date('Y-m-d H:i:s', time());
            $updateData ['created_by'] = Auth::id();;

            $vulsData['description'] = $request->description;
            $vulsData['payload'] = $request->payload;
            $vulsData['form_url'] = $request->form_url;
            $vulsData['url_parms'] = $request->url_parms;


            $vulsData['status'] = $state;
            $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
            $vulsData['category_id'] = !empty($request->categoryId) ? $request->categoryId : $vuls[0]->category_id;
            $recordUdp = DB::table('vuls_record')->insert(
                $updateData
            );

            $vulsUdp = DB::table('vuls')
                ->where('id', $request->id)
                ->update($vulsData);
        }
        //存入邮件任务
        if ($oporate=='check'){
            $config = config('email.cansend');
            if ($config) {
                $updatedVuls = Vuls::find($request->id);
                $vulevel = DB::table('level')
                    ->where('id', '=', $updatedVuls->level_id)
                    ->first();
                //查询app，ogz相关信息，以及相关人员信息
                $vuogz = DB::table('app')
                    ->join('ogz as a', 'app.ogz_id', '=', 'a.id')
                    ->where('app.id', '=', $updatedVuls->app_id)
                    ->whereIn('app.id',access()->hasApps())
                    ->select('app.name as appname', 'app.user_id as  appusers', 'a.name as ogzname')
                    ->get()
                    ->toArray();
                $appuser = isset($vuogz[0]) ? $vuogz[0]->appusers : '';
                if ($appuser) {
                    $appUserId = explode(',', $appuser);
                    $appUserInfo = DB::table('users')
                        ->whereIn('id', $appUserId)
                        ->get()
                        ->toArray();
                    if ($appUserInfo) {
                        $send = "";
                        $username = "";
                        foreach ($appUserInfo as $value) {
                            if ($value->email) {
                                $send .= decrypt_func($value->email, $value->name) . ",";
                                $username .= $value->real_name ? $value->real_name : $value->name;
                                $username .= ",";
                            }
                        }
                        $send = trim($send, ",");
                        $username = trim($username, ",");
                        if ($send) {
                            $vulsInfo = array();
                            $vulsInfo['title'] = $updatedVuls->title;//漏洞名称
                            $vulsInfo['vulsid'] = $updatedVuls->id;//漏洞名称
                            $vulsInfo['vuls_number'] = $updatedVuls->vuls_number;//漏洞id
                            $vulsInfo['level_name'] = $vulevel->name;//漏洞等级
                            $vulsInfo['level_id'] = $vulevel->id;//漏洞等级
                            $vulsInfo['deadline'] = $vulevel->term;//漏洞修复时限
                            $vulsInfo['sendtype'] = 1;//邮件类型
                            $vulsInfo['useremail'] = $send;//收件人
                            $vulsInfo['user'] = $username;//收件人
                            $vulsInfo['source'] = $vuls[0]->source;//漏洞来源
                            $vulsInfo['description'] = $updatedVuls->description;//漏洞副标题
                            $vulsInfo['user_id'] = $updatedVuls->user_id;;//提交人
                            $vulsInfo['appname'] = $vuogz[0]->appname;//漏洞所属系统
                            $vulsInfo['appid'] = $updatedVuls->app_id;//漏洞所属系统
                            if (DB::table('task')->insert(
                                $vulsInfo
                            )){
                                \Log::info('vul['.$request->id.']task email success.');
                            }

                        }else{
                            \Log::info(' users email is invalid.');
                        }
                    }else{
                        \Log::info('app users is empty.');
                    }
                }
            }else{
                \Log::info('env config MAIL_CANSEND=false,please config it true.');
            }
        }
        return redirect('/admin/vulsList');

    }

    /**
     * 已审核步骤中1个个操作：确认提交
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function checkedForm(Request $request)
    {
        $validator = $this->validate($request, [
            'description' => 'required|max:255',
            'id' => 'required|integer',
            'credit' => 'required|integer',
            'reward' => 'required|integer',
            'level' => 'required|integer',
        ],
            [
                "description.max" => "描述长度不可以超过225个字符<br>",
                "description.required" => "描述为必填项<br>",
                "id.required" => "请提交对应漏洞项<br>",
                "id.integer" => "漏洞项类型不正确<br>",
                "credit.integer" => "非法积分值<br>",
                "reward.integer" => "非法金币值<br>",
                "level.integer" => "请选择漏洞等级<br>",
                "credit.required" => "请选择积分<br>",
                "reward.required" => "请选择金币<br>",
                "level.required" => "请选择漏洞等级<br>",
            ]);
        if ($request->level) {
            $max_min = $this->getMaxAndMin($request->level);
            if (!$max_min) {
                return back()->with("flow_error", "当前漏洞等级不存在");
                exit();
            }
            if ($request->credit) {
                $creditChecked = $this->checkMaxAndMin($max_min, (int)$request->credit, "credit");
                if (!$creditChecked) {
                    return back()->with("flow_error", "积分必须在给定范围内");
                    exit();
                }
                $vulsData['credit'] = $request->credit;//漏洞积分更新
                $updateData['credit'] = $request->credit;//漏洞积分更新
            }
            if ($request->reward) {
                $rewardChecked = $this->checkMaxAndMin($max_min, (int)$request->reward, "reward");
                if (!$rewardChecked) {
                    return back()->with("flow_error", "金币必须在给定范围内");
                    exit();
                }
                $vulsData['reward'] = $request->reward;//漏洞金币更新
                $updateData['reward'] = $request->reward;//漏洞金币更新
            }
            $vulsData['level_id'] = $request->level;//漏洞金币更新
        }
        $status = config('app.vul');//获取状态码配置

        $app_id = Vuls::where(array('id' => $request->id))
            ->select('app_id', 'status')
            ->get();
        $app_id = $app_id->toArray();
        $visit = $this->legal($app_id[0]['status'], "checked");//判断当前的页面访问是否合法
        if (!$visit) {
            return abort(404);
            exit();
        }
        $updateData = array();
        if (count($app_id)) {
            $updateData = [
                'vuls_id' => $request->id,
                'app_id' => $app_id[0]['app_id'],
                'content' => $request->description,
            ];
        } else {
            $updateData = [
                'vuls_id' => $request->id,
                'content' => $request->description,
            ];
        }
        $updateData ['vuls_status'] = $status["status"]["2"]["id"];;
        $updateData ['created_at'] = date('Y-m-d H:i:s', time());
        $updateData ['created_by'] = Auth::id();;
        $updateData['reward'] = $request->credit;
        $updateData['credit'] = $request->reward;
        $vulsData['status'] = $status["status"]["2"]["id"];//漏洞状态更新为待确认
        $vulsData['updated_at'] = date('Y-m-d H:i:s', time());;
        $vulsData['credit'] = $request->credit;//漏洞积分更新
        $vulsData['reward'] = $request->reward;//漏洞金币更新
        $vulsData['level_id'] = $request->level;//漏洞等级更新
        $recordUdp = DB::table('vuls_record')->insert(
            $updateData
        );
        $vulsUdp = DB::table('vuls')
            ->where('id', $request->id)
            ->update($vulsData);

        return redirect('/admin/vulsList');

    }

    /**获取漏洞关联的评分和金币的最大最小值
     * @param $id
     * @return mixed
     */
    public function getMaxAndMin($id)
    {
        $vuls = Level::where('id', '=', $id)
            ->select('level.min_reward', 'level.max_reward', 'min_integ', 'max_integ')
            ->get()
            ->toArray();
        if (empty($vuls)) {
            return false;
        } else {
            $value['credit_max'] = $vuls[0]['max_integ'];
            $value['credit_min'] = $vuls[0]['min_integ'];
            $value['reward_max'] = $vuls[0]['max_reward'];
            $value['reward_min'] = $vuls[0]['min_reward'];
            return $value;
        }

    }

    /**检查是否在给定的范围内
     * @param $aim
     * @param $check
     * @param $type
     * @return bool
     */
    public function checkMaxAndMin($aim, $check, $type)
    {
        if ($check >= $aim[$type . "_min"] && $check <= $aim[$type . "_max"]) {
            return true;
        } else {
            return false;
        }
    }

    /**根据id查询漏洞相关信息
     * @param $id
     * @return bool
     */
    public function getVuls($id)
    {
        if (!(int)$id) {
            return false;
            exit();
        }
        return $vuls = DB::table('vuls')
            ->leftJoin('users', 'users.id', '=', 'vuls.user_id')
            ->where('vuls.id', '=', $id)
            ->whereIn('vuls.app_id',access()->hasApps())
            ->select("vuls.*", "users.source")
            ->get();
    }

    /**访问合法性检查
     * @param $state  当前的漏洞状态
     * @param $current 当前的访问页面
     * @return bool
     */
    public function legal($state, $current)
    {
        $status = [
            '0' => 'check',
            '1' => 'checked',
            '2' => 'ensure',
            '3' => 'repairshow',
            '4' => 'confirmshow',
            '5' => 'solved',//已解决
            '6' => 'shut',//已关闭
            '7' => 'appeal',//申诉中
            '8' => 'ignore', //已忽略
            '11' => 'noEffect', //无影响
        ];
        if (array_key_exists($state, $status)) {
            $visit = strtolower($status[$state]);
            $current = strtolower($current);
            if ($visit == $current) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**漏洞分发中，查询已经分发的人员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxVuls(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            $id = (int)$request->vuls_id;
            $vuls = DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->select("users_id", "name")
                ->get()
                ->toArray();
            if (count($vuls)) {
                return response()->json(['data' => $vuls, 'status' => 2], 200);
                exit();
            } else {
                return response()->json(["msg" => "未分发", 'status' => 2, 200]);
            }

        }
    }

    /**ajax访问
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxForm(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            $id = (int)$request->level;
            $level = Level::where('id', $id)
                ->select('min_reward', 'max_reward', 'min_integ', 'max_integ')
                ->get();
            return response()->json($level, 200);
        }
    }

    /**获取人员信息
     * @param Request $request
     * @status 1代表未查到相关的信息，或者查询错误 2，表示查询到相关信息
     */
    public function getUsers(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            $name = $request->name;
            if (!$name) {
                return response()->json(['msg' => "未找到相关用户", 'status' => 1], 200);
                exit();
            }
            $api = new Distribute();
            $user = $api->getUser($name);
            \Log::info('distribute userinfo '.json_encode($user));
            if (count($user)) {
                $return = array();
                $return["vcName"] = isset($user['vcName'])?$user['vcName']:"";
                $return["vcAccount"] = isset($user['vcAccount'])?$user['vcAccount']:"";
                $return["vcEmail"] = isset($user['vcEmail'])?$user['vcEmail']:"";
                $return["vcFullName"] = isset($user['vcFullName'])?$user['vcFullName']:"";
                return response()->json(['data' => $return, 'status' => 2], 200);
                exit();
            } else {
                return response()->json(["msg" => "未找到相关用户", 'status' => 1, 200]);
            }
        }

    }

    /**漏洞分发添加人员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function distribute(Request $request)
    {

        if ($request->getMethod() == 'POST') {
            $id = (int)$request->vuls_id;
            $name = trim($request->name,",");
            // $name="zl01,zl02";
            $users = explode(",", $name);
            //查询当前已分发的人数
            $c_vuls = DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->select("users_id", "name")
                ->get()
                ->toArray();
            if (count($c_vuls) >= 10) {
                \Log::info('vus['.$id.'] people number to max');
                return response()->json(['msg' => '分发人数已达到上限', 'status' => 1], 200);
            }
            $total = count($users) + count($c_vuls);
            if (count($c_vuls) >= 10) {
                \Log::info('vus['.$id.'] people number to 10');
                return response()->json(['msg' => '分发人数上限为10人', 'status' => 1], 200);
            }
            /*=========================查询该用户是否已分发===========================*/
            $c_user = DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->whereIn('name', $users)
                ->select("users_id", "name")
                ->get()
                ->toArray();
            $already = "";
            if (count($c_user)) {
                foreach ($c_user as $names) {
                    $already .= $names->name . ",";
                }
                $already = trim($already, ",");
                \Log::info('vus['.$id.'] people'.$already.' has distributed');

                return response()->json(['msg' => $already . '用户已分发', 'status' => 1], 200);
            }
            $db_user = new Distribute();
            /*+-------------查询该用户是否存在----------------+*/
            $user = User::withTrashed()
                ->whereIn('name', $users)
                ->select("id", "name","status")
                ->get();
            $exist=array();//已经存在的
            $noexist=array();//尚未存在的

            if($user){
                foreach ($user as $a)
                {
                    $exist[]=$a->name;
                }
                $noexist=array_diff($users, $exist);
            }else{
                $noexist= $users;
            }
            $vuls_info = DB::table('vuls')
                ->where('vuls.id', '=', $id)
                ->first();
            if ($noexist) {//用户都不存在

                foreach ($noexist as $value){
                    \Log::info('vul['.$id.'] distribute user is'.$value);
                    $user_info = $db_user->getUser($value);
                    // $user_info = ['vcName'=>'zl01','vcEmail'=>'zl@distribute.com','vcWorkPhone'=>'15094001356','vcSecondName'=>'lee','vcBirthday'=>'0903','cSex'=>'man'];
                    //创建用户信息
                    if ($user_info) {
                        DB::beginTransaction();
                        $new['name'] = $value;
                        $new['real_name'] = isset($user_info['vcName'])?$user_info['vcName']:"";
                        $new['email'] =isset($user_info['vcEmail']) && !empty($user_info['vcEmail'])? encrypt_func($user_info['vcEmail'], $value):""; //加密邮箱
                        $new['phone'] = isset($user_info['vcWorkPhone']) && !empty($user_info['vcWorkPhone'])?encrypt_func($user_info['vcWorkPhone'], $value):"";//加密电话
                        $new['status'] = 1;//免激活
                        $new_result = DB::table('users')->insertGetId(
                            $new
                        );
                        $userForRole = User::find($new_result);
                        if ($userForRole){
                            //分配业务方角色
                            $db_user->roleDefault($userForRole);
                            //用户扩展信息
                            $new_ext['user_id'] = $new_result;
                            $new_ext['alias'] = isset($user_info['vcSecondName'])?$user_info['vcSecondName']:"";
                            $new_ext['birth'] = isset($user_info['vcBirthday'])?$user_info['vcBirthday']:"";
                            $new_ext['sex'] = isset($user_info['cSex'])?$user_info['cSex']:"";
                            $newext_result = DB::table('user_ext')->insert(
                                $new_ext
                            );
                        }
                        //  漏洞分发
                        $dist_info = array();
                        $dist_info["vuls_id"] = $vuls_info->id;
                        $dist_info["app_id"] = $vuls_info->app_id;
                        $dist_info["users_id"] = $new_result;
                        $dist_info["name"] = $value;
                        $dist_info["handle"] = Auth::id();
                        $record_result = DB::table('distribute')->insert(
                            $dist_info
                        );
                        if ($newext_result && $record_result) {

                            //*漏洞分发记录
                            $vuls_r = array();
                            $vuls_r['app_id'] = $vuls_info->app_id;
                            $vuls_r['vuls_id'] = $vuls_info->id;
                            $vuls_r['vuls_status'] = $vuls_info->status;
                            $vuls_r['content'] = "漏洞分发给" . $value;
                            $vuls_r['reward'] = $vuls_info->reward;
                            $vuls_r['credit'] = $vuls_info->credit;
                            $vuls_r['distribute_id'] = Auth::id();
                            $vuls_r['user_id'] = $new_result;
                            $vuls_r['created_by'] = Auth::id();
                            $record_result = VulsRecord::create($vuls_r);
                            DB::commit();

                        } else {
                            DB::rollback();
                            return response()->json(['msg' => '用户信息更新失败', 'status' => 1], 200);
                        }

                    } else {
                        return response()->json(['msg' => '未查到相关用户信息', 'status' => 1], 200);
                    }
                }

            }
            if ($user) { //用户都存在
                //  漏洞分发
                DB::beginTransaction();
                 foreach ($user as $value){
                     $user = User::withTrashed()->find($value->id);
                     //启用被禁用用户，取消其他所有，授予默认角色
                     if ($value->status==0){
                         //激活
                         $user->status = 1;
                         $user->deleted_at = NULL;
                         $user->save();
                         //授权
                         $db_user->roleDefault($user);
                     }
                     //没有默认权限，授予对应权限
                     if (!$user->hasRole($db_user->defaultRoleId)){
                         $user->attachRole($db_user->defaultRoleId);
                     }
                     $dist_info = array();
                     $dist_info["vuls_id"] = $vuls_info->id;
                     $dist_info["app_id"] = $vuls_info->app_id;
                     $dist_info["users_id"] = $value->id;
                     $dist_info["name"] = $value->name;
                     $dist_info["handle"] = Auth::id();
                     $record_results = DB::table('distribute')->insert(
                         $dist_info
                     );
                     if($record_results){
                         //漏洞分发记录
                         $vuls_r = array();
                         $vuls_r['app_id'] = $vuls_info->app_id;
                         $vuls_r['vuls_id'] = $vuls_info->id;
                         $vuls_r['vuls_status'] = $vuls_info->status;
                         $vuls_r['content'] = "漏洞分发给" . $value->name;
                         $vuls_r['reward'] = $vuls_info->reward;
                         $vuls_r['credit'] = $vuls_info->credit;
                         $vuls_r['distribute_id'] = Auth::id();
                         $vuls_r['user_id'] = $value->id;
                         $vuls_r['created_by'] = Auth::id();
                         $record_result = VulsRecord::create($vuls_r);
                         DB::commit();
                     }else{
                         DB::rollback();
                         return response()->json(['msg' => '漏洞分发失败', 'status' => 1], 200);
                     }


                 }

            }
            $d_vuls = DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->select("users_id", "name")
                ->get()
                ->toArray();
            return response()->json(['msg' => '漏洞分发成功', 'data' => $d_vuls, 'status' => 2], 200);

        }

    }

    /**漏洞分发添加人员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function distridel(Request $request)
    {

        if ($request->getMethod() == 'POST') {
            $id = (int)$request->vuls_id;
            $name = $request->user;
            //查询当前已分发的人数
            $c_vuls = DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->where("users_id", '=', $name)
                ->first();
            if (!count($c_vuls)) {
                return response()->json(['msg' => '该用户不存在', 'status' => 1], 200);
                exit();
            }
            $vuls_info = DB::table('vuls')
                ->where('vuls.id', '=', $id)
                ->first();

            DB::beginTransaction();
            DB::table('distribute')
                ->where('vuls_id', '=', $id)
                ->where("users_id", '=', $name)
                ->delete();

            //*漏洞分发记录

            $vuls_r = array();
            $vuls_r['app_id'] = $vuls_info->app_id;
            $vuls_r['vuls_id'] = $vuls_info->id;
            $vuls_r['vuls_status'] = $vuls_info->status;
            $vuls_r['content'] = "将" . $c_vuls->name . "从分发的漏洞中删除掉";
            $vuls_r['reward'] = $vuls_info->reward;
            $vuls_r['credit'] = $vuls_info->credit;
            $vuls_r['distribute_id'] = Auth::id();
            $vuls_r['user_id'] = $name;
            $vuls_r['created_by'] = Auth::id();
            $record_result = VulsRecord::create($vuls_r);
            if ($record_result) {
                $d_vuls = DB::table('distribute')
                    ->where('vuls_id', '=', $id)
                    ->select("users_id", "name")
                    ->get()
                    ->toArray();
                DB::commit();
                return response()->json(['msg' => '删除成功', 'data' => $d_vuls, 'status' => 2], 200);

            } else {
                DB::rollback();
                return response()->json(['msg' => '删除失败', 'status' => 1], 200);
            }

        }
    }
    /**
     * 申请延时
     */
    public function delay(Request $request){
        $data['code'] = 0;
        //时间和原因不能为空
        if (empty($request->delayed_at)){
            $data['code'] = 422;
            $data['msg'] = '申请时间不能为空';
            return back()->withErrors('申请时间不能为空');

        }
        if (empty($request->reason)){
            $data['code'] = 422;
            $data['msg'] = '理由不能为空';
            return back()->withErrors('理由不能为空');

        }
        $service = new Delay();
        try{

            $service->apply($request);
        }catch (\Exception $e){
            $data['code'] = 500;
            $data['msg']  = $e->getMessage();
            return back()->withErrors($e->getMessage());
        }
        return redirect('/admin/vulsList');
    }

    /**
     * 获取一条延时信息
     */
    public function getOneDelay (Request $request){
        $data = ['code'=>0];
        $delay = VulsDelay::where(['vuls_id'=>$request->vuls_id])->first();
        $begin_time = VulsDelay::getBeginTime($request->vuls_id);

        if (empty($delay) && empty($begin_time)){
            $data['code'] = 500;
            $data['msg']  = '该漏洞没有申请延期';
        } else{
            $delayed_at = isset($delay->delayed_at) ? $delay->delayed_at : '';
            $reason = isset($delay->reason) ? $delay->reason : '';

            $data['data'] = ['delayed_at'=>$delayed_at,'reason'=>$reason,'begin_time'=>$begin_time,'to_begin_time' => Carbon::parse($begin_time)->addDay()];
        }
        return $data;
    }
    /**
     * 审核一条延时信息
     */
    public function auditDelay (Request $request){
        $data = ['code'=>0];
        $delay = VulsDelay::where(['vuls_id'=>$request->vuls_id])->first();

        if (empty($delay)){
            $data['code'] = 500;
            $data['msg']  = '该漏洞没有申请延期';
        } else{
            try{

                Delay::audit($request);
            }catch (\Exception $e){
                $data['code'] = 500;
                $data['msg']  = $e->getMessage();
            }
        }
        if ($data['code'] > 0){
            return back()->withErrors($data['msg']);
        }
        return redirect('/admin/vulsList');
    }

    /**
     * 申请延期显示回驳回话记录
     */
    function applyPage (Request $request) {
        $category = new Category;
        $apps = $this->userLinks();
        $categorys = $category->getCategoryInfo();
        $users = DB::table('users')->select('id', 'real_name', 'name')->get();
        $levels = DB::table('level')->select('id', 'level', 'name')->get();
        $vulStatus = config('app.vul.status');
        $item = Vuls::where(['id' => $request->vuls_id])->whereIn('app_id', $apps['apps'])->first();
        if ($item) {

            $item->content = overwriteConetnt($request, $item->content, Auth::user()->real_name);
            //价值
            $item->vlus_value = Vuls::getValue($item->level_id);
            //检查项
            if (intval($item->check_id) > 0) {
                $item->checkStr = CheckOption::where(['id' => $item->check_id])->value('name');
            }
            //参考资料
            $item->ref = Knowledge::where(['category_id' => $item->category_id])->get();
            //延期信息
            $delay =$this->getOneDelay($request);
            if ($delay['code'] != 0){
                abort($delay['code'],$delay['msg']);
            }
            $item->delay = $delay['data'];
            //对话记录
            $item->content = VulsDelay::getDelayContent($item->id);
        }
        return view('backend.flaw.applydelay', [
            'item' => $item,
            'action' => 'update',
            'categorys' => $categorys,
            'users' => $users,
            'levels' => $levels,
            'apps' => DB::table('app')->select('id', 'ogz_id', 'name')->whereIn('id', $apps['apps'])->get(),
            'vulstatus' => $vulStatus,
            'audit' => intval($request->audit)
        ]);
    }

}


